<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <template v-if="type == 'password'">
      <t-form-item name="username">
        <t-input v-model="formData.username" size="large" :placeholder="`${t('pages.login.input.username')}`">
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input
          v-model="formData.password"
          size="large"
          :type="showPsw ? 'text' : 'password'"
          clearable
          :placeholder="`${t('pages.login.input.password')}`"
        >
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="code">
        <t-input v-model="formData.code" size="large" :placeholder="`${t('pages.login.input.verification')}`">
          <template #prefix-icon>
            <t-icon name="secured" />
          </template>
        </t-input>
        <img @click="unGetCaptchaImage" class="captcha-img" :src="captchaImage" alt="" />
      </t-form-item>

      <div class="check-container remember-pwd">
        <t-checkbox>{{ t('pages.login.remember') }}</t-checkbox>
      </div>
    </template>

    <t-form-item class="btn-container">
      <t-button block size="large" type="submit"> {{ t('pages.login.signIn') }} </t-button>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { getCaptchaImage } from '@/api/system/user';
import { useRoute, useRouter } from 'vue-router';
import { t } from '@/locales';
import { useUserStore } from '@/store';
import { MessagePlugin } from 'tdesign-vue-next';

const userStore = useUserStore();

const INITIAL_DATA = {
  username: 'admin',
  password: 'admin123',
  code: '',
  uuid: '',
};

const FORM_RULES = {
  username: [{ required: true, message: t('pages.login.required.username'), type: 'error' }],
  password: [{ required: true, message: t('pages.login.required.password'), type: 'error' }],
  code: [{ required: true, message: t('pages.login.required.verification'), type: 'error' }],
};

const type = ref('password');

const form = ref();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);
const router = useRouter();
const route = useRoute();
const captchaImage = ref('');

/**
 * 获取图形验证码
 */
const unGetCaptchaImage = async () => {
  try {
    const res = await getCaptchaImage();
    formData.value.uuid = res.uuid;
    captchaImage.value = 'data:image/png;base64,' + res.img;
  } catch (e) {
    console.log(e);
  }
};

const onSubmit = async () => {
  const validResult = await form.value.validate();
  if (validResult === true) {
    try {
      await userStore.login(formData.value);
      MessagePlugin.success('登录成功');
      const redirect = route.query.redirect as string;
      const redirectUrl = redirect ? decodeURIComponent(redirect) : '/home';
      router.push(redirectUrl);
    } catch (e) {
      unGetCaptchaImage();
      console.error(e);
    }
  }
};

onMounted(() => {
  unGetCaptchaImage();
});
</script>

<style lang="less" scoped>
@import '../index.less';
</style>
